package com.example.test4

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
//import android.widget.GridLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.children
//import com.example.test4.model.CardMatchingGame
import androidx.gridlayout.widget.GridLayout
import com.example.test4.model.CardMatchingGame
import com.example.test4.model.User


class MainActivity : AppCompatActivity(), View.OnClickListener{
    lateinit var game: CardMatchingGame
    var cardButtons=mutableListOf<Button>()
    lateinit var scoreTextView: TextView

    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)
        val gridLayout=findViewById<GridLayout>(R.id.gridLayout)
       scoreTextView=findViewById(R.id.scoreTextView)
        for(v in gridLayout.children)
        {
           if(v is Button){
               v.setOnClickListener (this)
               cardButtons.add(v)
           }
        }
        game= CardMatchingGame(cardButtons.count())
        updataUI()
        val reset=findViewById<Button>(R.id.button_reset)
        val back=findViewById<Button>(R.id.button_back)
        reset.setOnClickListener {
            game= CardMatchingGame(cardButtons.count())
            updataUI()
        }
        // 在 back.setOnClickListener 中
        back.setOnClickListener {
            val intent = Intent()
            intent.putExtra(FIRST_MSG, game.score)
            setResult(2, intent)
            finish()
        }
    }
    fun updataUI(){
        for(button in cardButtons){
            val index=cardButtons.indexOf(button)
            val card=game.cardAtIndex(index)
            button.isEnabled=!card.isMatched
            if(card.isChosen){
                button.text=card.toString()
                button.setBackgroundColor(Color.WHITE)
            }else{
                button.text=""
                button.setBackgroundResource(R.drawable.card)
            }
        }
        scoreTextView.text=game.score.toString()
    }
    override fun onClick(v: View) {
        // 处理点击事件的逻辑（例如：判断点击的是哪张牌，通知游戏逻辑处理）
        if (v is Button) {
            val index = cardButtons.indexOf(v) // 获取点击的按钮在列表中的索引
            game.chooseCardAtIndex(index) // 调用游戏逻辑处理选中的牌
            updataUI() // 更新界面显示
        }
    }

}